package com.zhxy.controller;

import java.nio.charset.StandardCharsets;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import com.zhxy.util.TokenUtil;
import com.zhxy.vo.PutPolicy;

@Controller  
public class TestController {

    private static final long EIGHT_HOURS = 1000L * 60 * 60 * 8; // 8 hours

	@RequestMapping("success")     
    public String start(HttpServletRequest request){  
		System.out.println("roderick");
        return "success_page";  
    }

    @RequestMapping("/get-token")
    public ResponseEntity<String> getUploadToken(HttpServletRequest request) {

        MediaType mediaType = new MediaType("application", "json", StandardCharsets.UTF_8);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(mediaType);
        String bucket = ServletRequestUtils.getStringParameter(request, "bucket",null);
        String key = ServletRequestUtils.getStringParameter(request, "key",null);
        String overwrite = ServletRequestUtils.getStringParameter(request, "overwrite", null);
        
        String test = "hahah";
        ResponseEntity<String> result = new ResponseEntity<String>(buildUploadToken(bucket, key, null, null, null),
                headers, HttpStatus.OK);
        return result;
    }

    private String buildUploadToken(String bucketName, String fileKey, String userid, String vid, String fileId) {
        // 构建视频上传策略
        PutPolicy putPolicy = new PutPolicy();

        // 上传到云存储的文件名
        if (null == fileKey || fileKey.isEmpty()) {
            putPolicy.setScope(bucketName);
        } else {
            putPolicy.setScope(bucketName + ":" + fileKey);
        }

        putPolicy.setOverwrite(1);
        // 上传请求授权的截止时间，UNIX时间戳，单位：毫秒。
        String deadline = String.valueOf(System.currentTimeMillis() + EIGHT_HOURS);
        putPolicy.setDeadline(deadline);

        // 设置callbackUrl参数
        // String callbackUrl = "http://my.polyv.net/wscallback/upload_video";
        // putPolicy.setCallbackUrl(callbackUrl);

        // 设置callbackBody参数
        // String callbackBody = "bucket=$(bucket)&key=$(key)&fname=$(fname)&hash=$(hash)&fsize=$(fsize)&url=$(url)&ip=$(ip)&userid="
        // + userid + "&vid=" + vid + "&fileid=" + fileId;
        // putPolicy.setCallbackBody(callbackBody);

        // 上传Token
        return TokenUtil.getUploadToken(putPolicy);
    }

}
